package com.geek.service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Collections;

public class RedisLock {


    /**
     * 枚举单例
     */
    private enum EnumSingleton {

        INSTANCE;

        private RedisLock instance;

        EnumSingleton() {
            instance = new RedisLock();
        }

        public RedisLock getInstance() {
            return instance;
        }
    }

    public static RedisLock getInstance() {
        return EnumSingleton.INSTANCE.getInstance();
    }


    private JedisPoolConfig config = new JedisPoolConfig();
    private JedisPool jedisPool = new JedisPool(config, "10.70.25.139", 6379 , 1000, "redis@20190312^");

    public boolean lock(String lockKey, int seconds) {
        try (Jedis jedis = jedisPool.getResource()) {
            // 返回 "OK": 获取锁成功
            return "OK".equals(jedis.set(lockKey, lockKey, "NX", "EX", seconds));
        }
    }

    /**
     * 释放锁
     */
    public boolean unlock(String lockKey) {
        String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + "return redis.call('del',KEYS[1]) else return 0 end";
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.eval(luaScript, Collections.singletonList(lockKey), Collections.singletonList(lockKey)).equals(1);
        }
    }
}
